/*
 *    Copyright (c) 2018-2025, cloud All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: cloud
 */

package com.fuyao.cloud.asset.purchaseApply.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fuyao.cloud.asset.constant.PurchaseConstant;
import com.fuyao.cloud.asset.dto.apply.PurchaseapplySearchDTO;
import com.fuyao.cloud.asset.entity.AssetPurchaseapplyList;
import com.fuyao.cloud.asset.enums.AssetStatusEnum;
import com.fuyao.cloud.asset.purchaseApplyList.service.AssetPurchaseapplyListService;
import com.fuyao.cloud.common.core.constant.CommonConstants;
import com.fuyao.cloud.common.core.controller.FlowableController;
import com.fuyao.cloud.common.core.flowable.enums.ProcessStatusEnum;
import com.fuyao.cloud.common.core.util.R;
import com.fuyao.cloud.common.data.datascope.DataScope;
import com.fuyao.cloud.common.data.mybatis.SpliceQueryWrapper;
import com.fuyao.cloud.common.data.resolver.NumberResolver;
import com.fuyao.cloud.common.log.annotation.SysLog;
import com.fuyao.cloud.asset.entity.AssetPurchaseapply;
import com.fuyao.cloud.asset.purchaseApply.service.AssetPurchaseapplyService;
import org.springframework.security.access.prepost.PreAuthorize;
import com.fuyao.cloud.common.excel.annotation.ResponseExcel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import com.fuyao.cloud.asset.vo.FyAssetPurchaseapplyExcelVO;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 采购申请
 *
 * @author 时间的朋友
 * @date 2021-11-22 13:58:37
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/fyassetpurchaseapply" )
@Api(value = "fyassetpurchaseapply", tags = "采购申请管理")
public class AssetPurchaseapplyController implements FlowableController {

    private final AssetPurchaseapplyService fyAssetPurchaseapplyService;
    private final AssetPurchaseapplyListService fyAssetPurchaseapplyListService;

    /**
     * 分页查询
     * @param page 分页对象
     * @param searchDTO 采购申请
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page" )
    @PreAuthorize("@pms.hasPermission('purchaseApply_fyassetpurchaseapply_view')" )
    public R getFyAssetPurchaseapplyPage(Page page, PurchaseapplySearchDTO searchDTO) {
        return R.ok(fyAssetPurchaseapplyService.page(page, SpliceQueryWrapper.spliceSearchCondition(searchDTO),searchDTO,new DataScope()));
    }


    /**
     * 通过id查询采购申请
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('purchaseApply_fyassetpurchaseapply_view')" )
    public R getById(@PathVariable("id" ) Long id) {
        return R.ok(fyAssetPurchaseapplyService.getById(id));
    }

	/**
	 * 通过id查询采购申请
	 * @param unid unid
	 * @return R
	 */
	@ApiOperation(value = "通过unid查询", notes = "通过unid查询")
	@GetMapping("/getUnidObj/{unid}" )
	@PreAuthorize("@pms.hasPermission('purchaseApply_fyassetpurchaseapply_view')" )
	public R getByUnId(@PathVariable("unid" ) String unid) {
		LambdaQueryWrapper<AssetPurchaseapply> lambdaQueryWrapper = Wrappers.<AssetPurchaseapply>query().lambda().eq(AssetPurchaseapply::getUnid, unid);
		AssetPurchaseapply purchaseapply = this.fyAssetPurchaseapplyService.getOne(lambdaQueryWrapper, false);
		return R.ok(this.fyAssetPurchaseapplyService.edit(purchaseapply.getId()));
	}

    /**
     * 新增采购申请
     * @param fyAssetPurchaseapply 采购申请
     * @return R
     */
    @ApiOperation(value = "新增采购申请", notes = "新增采购申请")
    @SysLog("新增采购申请" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('purchaseApply_fyassetpurchaseapply_add')" )
    public R save(@RequestBody AssetPurchaseapply fyAssetPurchaseapply) {
		fyAssetPurchaseapplyService.save(fyAssetPurchaseapply);
		return R.ok(fyAssetPurchaseapply);
    }

	/**
	 * 新增采购申请
	 * @param childList 采购申请
	 * @return R
	 */
	@ApiOperation(value = "新增采购申请的子数据", notes = "新增采购申请")
	@SysLog("新增采购申请子数据" )
	@PostMapping("addChildList")
	public R saveChildList(@RequestBody List<AssetPurchaseapplyList> childList) {
		AssetPurchaseapply purchaseapply=null;
		for (int i = 0; i < childList.size(); i++) {
			AssetPurchaseapplyList purchaseapplyList=childList.get(i);
			if (purchaseapply==null){
				purchaseapply=this.fyAssetPurchaseapplyService.getOne(Wrappers.<AssetPurchaseapply>lambdaQuery().
						eq(AssetPurchaseapply::getBatchnumber,purchaseapplyList.getBatchnumber()));
			}
			purchaseapplyList.setParentId(purchaseapply.getId());
			purchaseapplyList.setParentCaseid(purchaseapply.getCaseid());
			purchaseapplyList.setStatus(purchaseapply.getStatus());
			purchaseapplyList.setAmount(purchaseapplyList.getPrice().multiply(new BigDecimal(purchaseapplyList.getQuantity())));
			this.fyAssetPurchaseapplyListService.save(purchaseapplyList);
		}
		return R.ok();
	}

    /**
     * 修改采购申请
     * @param fyAssetPurchaseapply 采购申请
     * @return R
     */
    @ApiOperation(value = "修改采购申请", notes = "修改采购申请")
    @SysLog("修改采购申请" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('purchaseApply_fyassetpurchaseapply_edit')" )
    public R updateById(@RequestBody AssetPurchaseapply fyAssetPurchaseapply) {
        return R.ok(fyAssetPurchaseapplyService.updateById(fyAssetPurchaseapply));
    }

    /**
     * 通过id删除采购申请
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除采购申请", notes = "通过id删除采购申请")
    @SysLog("通过id删除采购申请" )
    @DeleteMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('purchaseApply_fyassetpurchaseapply_del')" )
    public R removeById(@PathVariable Long id) {
        return R.ok(fyAssetPurchaseapplyService.removeById(id));
    }


	@ApiOperation(value = "批量删除采购申请", notes = "批量删除采购申请")
	@SysLog("批量删除采购申请" )
	@DeleteMapping("/batchDelete" )
	@PreAuthorize("@pms.hasPermission('purchaseApply_fyassetpurchaseapply_del')" )
	public R batchDelete(@RequestBody List<Long> ids) {
		return fyAssetPurchaseapplyService.batchDelete(ids);
	}

    /**
     * 导出excel 表格
     * @param searchDTO 查询条件
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('purchaseApply_fyassetpurchaseapply_export')" )
    public List<FyAssetPurchaseapplyExcelVO> export(PurchaseapplySearchDTO searchDTO) {
        return fyAssetPurchaseapplyService.listExcel(SpliceQueryWrapper.spliceSearchCondition(searchDTO));
    }

	/**
	 * 获取批号
	 * 获取本地（resources）文件
	 */
	@GetMapping("/getBatchNumber")
	public R<String> getBatchNumber() {
		return R.ok(NumberResolver.getCodeByDateTime("",10000,5));
	}

	@GetMapping("/create")
	@PreAuthorize("@pms.hasPermission('purchaseApply_fyassetpurchaseapply_add')")
	public R create() {
		return R.ok(this.fyAssetPurchaseapplyService.create());
	}

	@GetMapping("/edit/{id}")
	@PreAuthorize("@pms.hasPermission('purchaseApply_fyassetpurchaseapply_edit')")
	public R edit(@PathVariable("id") Long id) {
		return R.ok(this.fyAssetPurchaseapplyService.edit(id));
	}


	@ApiOperation(value = "分页查询带明细信息", notes = "分页查询带明细信息")
	@GetMapping("/getApplyPage" )
	@PreAuthorize("@pms.hasPermission('purchaseApply_fyassetpurchaseapply_view')" )
	public R getApplyPage(Page page, AssetPurchaseapply entity) {
		return R.ok(fyAssetPurchaseapplyService.getApplyPage(page, Wrappers.query(entity),entity));
	}

	/**
	 * 提交采购申请审结
	 * @param purchaseapply 采购申请对象
	 * @return R
	 */
	@ApiOperation(value = "提交采购申请审结", notes = "提交采购申请审结")
	@SysLog("提交采购申请审结" )
	@PostMapping("commit")
	public R commit(@RequestBody AssetPurchaseapply purchaseapply) {
		return R.ok(this.fyAssetPurchaseapplyService.commit(purchaseapply));
	}

	@ApiOperation(value = "起草环节结束回调方法", notes = "起草环节结束回调方法")
	@PostMapping(value = "/draftEndCallback", produces = "application/json")
	@Override
	public R draftEndCallback(HttpServletRequest request, @RequestBody Map<String, Object> params) {
		if (params.containsKey("businessKey")) {
			String id = CollUtil.getLast(StrUtil.split(params.get("businessKey") + "", ":"));
			LambdaQueryWrapper<AssetPurchaseapply> lambdaQueryWrapper = Wrappers.<AssetPurchaseapply>query().lambda().eq(AssetPurchaseapply::getId, id);
			AssetPurchaseapply purchaseapply = this.fyAssetPurchaseapplyService.getOne(lambdaQueryWrapper, false);
			Assert.isTrue(ObjectUtils.isNotEmpty(purchaseapply), String.format("未找到对应的业务数据：%s", id));
			purchaseapply.setStatus(AssetStatusEnum.PROCESSING.getCode());
			this.fyAssetPurchaseapplyService.updateById(purchaseapply);
			return R.ok(purchaseapply,"修改状态成功");
		}
		return R.ok(CommonConstants.SUCCESS,"起草环节结束回调方法");
	}

	@ApiOperation(value = "回退至起草环节回调方法", notes = "回退至起草环节回调方法")
	@PostMapping(value = "/returnCallback", produces = "application/json")
	@Override
	public R returnCallback(HttpServletRequest request, @RequestBody Map<String, Object> params) {
		if (params.containsKey("businessKey")) {
			String id = CollUtil.getLast(StrUtil.split(params.get("businessKey") + "", ":"));
			LambdaQueryWrapper<AssetPurchaseapply> lambdaQueryWrapper = Wrappers.<AssetPurchaseapply>query().lambda().eq(AssetPurchaseapply::getId, id);
			AssetPurchaseapply purchaseapply = this.fyAssetPurchaseapplyService.getOne(lambdaQueryWrapper, false);
			Assert.isTrue(ObjectUtils.isNotEmpty(purchaseapply), String.format("未找到对应的业务数据：%s", id));
			purchaseapply.setStatus(AssetStatusEnum.DRAFT.getCode());
			this.fyAssetPurchaseapplyService.updateById(purchaseapply);
			return R.ok(purchaseapply,"修改状态成功");
		}
		return R.ok(CommonConstants.SUCCESS,"回退至起草环节回调方法");
	}

	@ApiOperation(value = "流程结束回调方法", notes = "流程结束回调方法")
	@PostMapping(value = "/callback", produces = "application/json")
	@Override
	public R finishEndCallback(HttpServletRequest request, @RequestBody Map<String, Object> params) {
		if (params.containsKey("businessKey")) {
			String id = CollUtil.getLast(StrUtil.split(params.get("businessKey") + "", ":"));
			LambdaQueryWrapper<AssetPurchaseapply> lambdaQueryWrapper = Wrappers.<AssetPurchaseapply>query().lambda().eq(AssetPurchaseapply::getId, id);
			AssetPurchaseapply purchaseapply = this.fyAssetPurchaseapplyService.getOne(lambdaQueryWrapper, false);
			Assert.isTrue(ObjectUtils.isNotEmpty(purchaseapply), String.format("未找到对应的业务数据：%s", id));
			String status = params.containsKey(ProcessStatusEnum.ZZ.toString()) ? AssetStatusEnum.INVALID.getCode() : AssetStatusEnum.APPROVE.getCode();
			purchaseapply.setStatus(status);
			this.fyAssetPurchaseapplyService.updateById(purchaseapply);
			return R.ok(purchaseapply,"修改状态成功");
		}
		return R.failed("未找到对应的业务数据");
	}
}
